package com.application.moneycalculator.db;

import com.application.moneycalculator.log.Log_;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class DataBaseProvider extends ContentProvider {
	
	private final String TAG = "DataBaseProvider";
	
	DataBaseOpenHelper mOpenHelper;
	
	private static final UriMatcher sUriMatcher;
	
	private static final int SETTINGS_CODE = 1;
	private static final int SETTINGS_ID_CODE = 2;
	
    private static final int EXPENSE_CODE = 3;
    private static final int EXPENSE_ID_CODE = 4;
	
	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(MoneyCalculator.AUTHORITY, "settings", SETTINGS_CODE);
        sUriMatcher.addURI(MoneyCalculator.AUTHORITY, "settings/#", SETTINGS_ID_CODE);
        
        sUriMatcher.addURI(MoneyCalculator.AUTHORITY, "expenses", EXPENSE_CODE);
        sUriMatcher.addURI(MoneyCalculator.AUTHORITY, "expenses/#", EXPENSE_ID_CODE);
    }

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		Log_.out(TAG, "delete");
		
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = -1;
        switch (sUriMatcher.match(uri)) {
        case SETTINGS_CODE:
            count = db.delete(DataBaseOpenHelper.SETTINGS_TABLE_NAME, where, whereArgs);
            break;
         
        case SETTINGS_ID_CODE:
        	 String settingsId = uri.getPathSegments().get(1);
             count = db.delete(DataBaseOpenHelper.SETTINGS_TABLE_NAME, MoneyCalculator.Settings._ID + "=" + settingsId
                     + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);

        case EXPENSE_CODE:
        	count = db.delete(DataBaseOpenHelper.EXPENSES_TABLE_NAME, where, whereArgs);
            break;
            
        case EXPENSE_ID_CODE:
        	String expenseId = uri.getPathSegments().get(1);
            count = db.delete(DataBaseOpenHelper.EXPENSES_TABLE_NAME, MoneyCalculator.Expense._ID + "=" + expenseId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		Log_.out(TAG, "insert");
		
		// Validate the requested uri
        if (sUriMatcher.match(uri) == SETTINGS_CODE) {
	        ContentValues values;
	        if (initialValues != null) {
	            values = new ContentValues(initialValues);
	        } else {
	            values = new ContentValues();
	        }
	
	        // Make sure that the fields are all set
	        if (values.containsKey(MoneyCalculator.Settings.SETTINGS_TABLE_FIELD_SETTING) == false) {
	            values.put(MoneyCalculator.Settings.SETTINGS_TABLE_FIELD_SETTING, MoneyCalculator.Settings.SETTINGS_SKIP_INTRODUCTION);
	        }
	        
	        if (values.containsKey(MoneyCalculator.Settings.SETTINGS_TABLE_FIELD_SETTING_VALUE) == false) {
	            values.put(MoneyCalculator.Settings.SETTINGS_TABLE_FIELD_SETTING_VALUE, 0);
	        }
	
	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        long rowId = db.insert(DataBaseOpenHelper.SETTINGS_TABLE_NAME, /*Notes.NOTE*/null, values);
	        if (rowId > 0) {
	            Uri newUri = ContentUris.withAppendedId(MoneyCalculator.Settings.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(newUri, null);
	            return newUri;
	        }
        } else if(sUriMatcher.match(uri) == EXPENSE_CODE) 
        {
        	ContentValues values;
	        if (initialValues != null) {
	            values = new ContentValues(initialValues);
	        } else {
	            values = new ContentValues();
	        }
	
	        // Make sure that the fields are all set
	        if (values.containsKey(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_DATE) == false) {
	            values.put(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_DATE, "0-0-0.0-0-0");
	        }
	        
	        if (values.containsKey(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_AMOUNT) == false) {
	            values.put(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_AMOUNT, 999);
	        }
	        
	        if (values.containsKey(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_CURRENCY) == false) {
	            values.put(MoneyCalculator.Expense.EXPENSES_TABLE_FIELD_EXPENSE_CURRENCY, "RUR");
	        }
	
	        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
	        long rowId = db.insert(DataBaseOpenHelper.EXPENSES_TABLE_NAME, /*Notes.NOTE*/null, values);
	        if (rowId > 0) {
	            Uri newUri = ContentUris.withAppendedId(MoneyCalculator.Expense.CONTENT_URI, rowId);
	            getContext().getContentResolver().notifyChange(newUri, null);
	            return newUri;
	        }
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		Log_.out(TAG, "onCreate");
		
		mOpenHelper = new DataBaseOpenHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
			String sortOrder) {
		Log_.out(TAG, "query");
		
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        
        switch (sUriMatcher.match(uri)) {
        case SETTINGS_CODE:
        	qb.setTables(DataBaseOpenHelper.SETTINGS_TABLE_NAME);
            break;
            
        case SETTINGS_ID_CODE:
        	qb.setTables(DataBaseOpenHelper.SETTINGS_TABLE_NAME);
            qb.appendWhere(MoneyCalculator.Settings._ID + "=" + uri.getPathSegments().get(1));
            break;

        case EXPENSE_CODE:
        	qb.setTables(DataBaseOpenHelper.EXPENSES_TABLE_NAME);
            break;
            
        case EXPENSE_ID_CODE:
        	qb.setTables(DataBaseOpenHelper.EXPENSES_TABLE_NAME);
            qb.appendWhere(MoneyCalculator.Expense._ID + "=" + uri.getPathSegments().get(1));
            break;
            
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        
		// Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
        
        c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		Log_.out(TAG, "update");
		
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = -1;
        switch (sUriMatcher.match(uri)) {
        case SETTINGS_CODE:
            count = db.update(DataBaseOpenHelper.SETTINGS_TABLE_NAME, values, where, whereArgs);
            break;
            
        case SETTINGS_ID_CODE:
            String settingId = uri.getPathSegments().get(1);
            count = db.update(DataBaseOpenHelper.SETTINGS_TABLE_NAME, values, MoneyCalculator.Settings._ID + "=" + settingId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        case EXPENSE_CODE:
            count = db.update(DataBaseOpenHelper.EXPENSES_TABLE_NAME, values, where, whereArgs);
            break;
            
        case EXPENSE_ID_CODE:
            String expensesId = uri.getPathSegments().get(1);
            count = db.update(DataBaseOpenHelper.EXPENSES_TABLE_NAME, values, MoneyCalculator.Expense._ID + "=" + expensesId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}
}
